package com.leyou.page.service;

import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> loadItemData(Long spuId) {
        // TODO 判断缓存是否存在，如果存在，直接返回
        // 查询数据集
        SpuDTO spu = itemClient.querySpuById(spuId);

        // 查询分类
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        // 查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecs(spu.getCid3());

        // 创建map，存放数据
        Map<String, Object> map = new HashMap<>();
        map.put("categories", categories);
        map.put("brand", brand);
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("detail", spu.getSpuDetail());
        map.put("skus", spu.getSkus());
        map.put("specs", specs);

        // TODO 放入redis缓存

        return map;
    }

    private static final String HTML_DIR = "C:\\lesson\\heima84\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long spuId) {
        // 1.模板名称
        String template = "item";
        // 2.上下文
        Context context = new Context();
        context.setVariables(loadItemData(spuId));
        // 3.关联一个本地文件
        File file = new File(HTML_DIR, spuId + ".html");
        // 4.创建输出流
        try (Writer writer = new PrintWriter(file, "UTF-8")) {
            // 利用引擎，渲染页面，把页面存入本地文件
            templateEngine.process(template, context, writer);
        } catch (Exception e) {
            throw new RuntimeException("创建静态页面失败！", e);
        }
    }

    public void deleteItemHtml(Long spuId) {
        File file = new File(HTML_DIR, spuId + ".html");
        if (file.exists()) {
            boolean isDelete = file.delete();
            if(!isDelete){
                // 删除失败，抛出异常
                throw new RuntimeException("删除静态页失败！");
            }
        }
    }
}
